<template>
  <div class="data-modeling-container">
    <el-row :gutter="20">
      <!-- 左侧导航 -->
      <el-col :span="4">
        <el-menu
          :default-active="activeMenu"
          @select="handleMenuSelect"
          class="side-menu"
        >
          <el-menu-item index="modelConfig">
            <i class="el-icon-setting"></i> 机理模型配置
          </el-menu-item>
          <el-menu-item index="dataBinding">
            <i class="el-icon-link"></i> 数据关联
          </el-menu-item>
          <el-menu-item index="visualization">
            <i class="el-icon-view"></i> 可视化设置
          </el-menu-item>
          <el-menu-item index="faultLocation">
            <i class="el-icon-warning"></i> 异常检测与定位
          </el-menu-item>
        </el-menu>
      </el-col>

      <!-- 右侧内容区 -->
      <el-col :span="20">
        <div v-show="activeMenu === 'modelConfig'">
          <model-config
            :device-types="deviceTypes"
            :templates="templates"
            :model-config="modelConfig"
            @save="saveModelConfig"
          />
        </div>
        <div v-show="activeMenu === 'dataBinding'">
          <data-binding
            :sensors="sensors"
            :model-params="modelConfig.params"
            :binding="dataBinding"
            :update-frequency="updateFrequency"
            @save="saveDataBinding"
          />
        </div>
        <div v-show="activeMenu === 'visualization'">
          <visualization-setting
            :structure="deviceStructure"
            :visual-config="visualConfig"
            @save="saveVisualConfig"
          />
        </div>
        <div v-show="activeMenu === 'faultLocation'">
          <fault-location
            :structure="deviceStructure"
            :sensor-data="sensorRealtimeData"
            :faults="faults"
            :binding="dataBinding"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { Message } from "element-ui";

// mock数据
const deviceTypes = [
  { label: "机床设备", value: "machine_tool" },
  { label: "泵类设备", value: "pump" },
  { label: "电机设备", value: "motor" },
  { label: "风机设备", value: "fan" },
  { label: "传送带", value: "belt" },
  { label: "压力容器", value: "pressure_vessel" },
  { label: "自定义类型", value: "custom" }
];

const templates = {
  machine_tool: [
    {
      name: "机械动力学模板",
      desc: "适用于机床设备的动力学分析和建模",
      params: [
        { key: "size", label: "设备尺寸(mm)", type: "input", default: "1200×800×600" },
        { key: "material", label: "材料属性", type: "select", options: ["钢材", "铝合金"], default: "钢材" },
        { key: "work_temp", label: "工作温度(℃)", type: "input", default: "25" },
        { key: "work_pressure", label: "工作压力(MPa)", type: "input", default: "0.8" }
      ]
    },
    {
      name: "热力学模板",
      desc: "适用于机床设备的热力学性能分析",
      params: [
        { key: "size", label: "设备尺寸(mm)", type: "input", default: "1200×800×600" },
        { key: "material", label: "材料属性", type: "select", options: ["钢材", "铝合金"], default: "铝合金" },
        { key: "work_temp", label: "工作温度(℃)", type: "input", default: "30" }
      ]
    }
  ],
  pump: [
    {
      name: "流体力学模板",
      desc: "适用于泵类设备的流体特性分析",
      params: [
        { key: "size", label: "设备尺寸(mm)", type: "input", default: "800×400×400" },
        { key: "material", label: "材料属性", type: "select", options: ["不锈钢", "铸铁"], default: "不锈钢" },
        { key: "flow_rate", label: "流量(m³/h)", type: "input", default: "10" }
      ]
    }
  ]
  // 其他类型可补充
};

const sensors = [
  { id: "vibration", name: "振动传感器", unit: "mm/s" },
  { id: "temperature", name: "温度传感器", unit: "℃" },
  { id: "pressure", name: "压力传感器", unit: "MPa" },
  { id: "current", name: "电流传感器", unit: "A" }
];

const deviceStructure = [
  {
    id: "main_body",
    name: "机身",
    children: [
      { id: "spindle", name: "主轴" },
      { id: "table", name: "工作台" }
    ]
  },
  {
    id: "drive_system",
    name: "驱动系统",
    children: [
      { id: "motor", name: "电机" },
      { id: "gearbox", name: "齿轮箱" }
    ]
  }
];

const faults = [
  {
    id: "fault1",
    partId: "spindle",
    name: "主轴异常振动",
    relatedParams: ["vibration", "temperature"]
  },
  {
    id: "fault2",
    partId: "motor",
    name: "电机过热",
    relatedParams: ["temperature", "current"]
  }
];

// 生成模拟实时数据
function genSensorRealtimeData(binding) {
  const data = {};
  Object.keys(binding).forEach(param => {
    const sensorId = binding[param];
    if (sensorId === "vibration") {
      data[param] = (Math.random() * 2 + 1).toFixed(2); // 1~3 mm/s
    } else if (sensorId === "temperature") {
      data[param] = (Math.random() * 20 + 20).toFixed(1); // 20~40℃
    } else if (sensorId === "pressure") {
      data[param] = (Math.random() * 0.5 + 0.5).toFixed(2); // 0.5~1.0MPa
    } else if (sensorId === "current") {
      data[param] = (Math.random() * 5 + 10).toFixed(2); // 10~15A
    }
  });
  return data;
}

export default {
  name: "DataStateModeling",
  components: {
    // 机理模型配置
    modelConfig: {
      props: ["deviceTypes", "templates", "modelConfig"],
      data() {
        return {
          selectedType: this.modelConfig.deviceType || "",
          selectedTemplate: this.modelConfig.templateName || "",
          paramValues: { ...this.modelConfig.params }
        };
      },
      watch: {
        selectedType(val) {
          this.selectedTemplate = "";
          this.paramValues = {};
        },
        selectedTemplate(val) {
          const tpl = this.getCurrentTemplate();
          if (tpl) {
            const params = {};
            tpl.params.forEach(p => {
              params[p.key] = p.default;
            });
            this.paramValues = params;
          }
        }
      },
      methods: {
        getCurrentTemplate() {
          return (
            (this.templates[this.selectedType] || []).find(
              t => t.name === this.selectedTemplate
            ) || null
          );
        },
        handleSave() {
          if (!this.selectedType || !this.selectedTemplate) {
            Message.warning("请选择设备类型和机理模板");
            return;
          }
          this.$emit("save", {
            deviceType: this.selectedType,
            templateName: this.selectedTemplate,
            params: { ...this.paramValues }
          });
        }
      },
      render(h) {
        return (
          <div>
            <el-card>
              <div slot="header">
                <span>选择设备类型</span>
              </div>
              <el-radio-group
                vModel={this.selectedType}
                style="margin-bottom: 16px;"
              >
                {this.deviceTypes.map(type => (
                  <el-radio-button label={type.value} key={type.value}>
                    {type.label}
                  </el-radio-button>
                ))}
              </el-radio-group>
              <div v-show={this.selectedType}>
                <div style="margin: 16px 0 8px;">选择机理模板</div>
                <el-row gutter={16}>
                  {(this.templates[this.selectedType] || []).map(tpl => (
                    <el-col span={12} key={tpl.name}>
                      <el-card
                        class={{
                          "template-card": true,
                          selected: this.selectedTemplate === tpl.name
                        }}
                        onClick={() => (this.selectedTemplate = tpl.name)}
                        style="cursor:pointer;margin-bottom:8px;"
                      >
                        <div>
                          <b>{tpl.name}</b>
                          <div style="font-size:12px;color:#888;">
                            {tpl.desc}
                          </div>
                        </div>
                      </el-card>
                    </el-col>
                  ))}
                </el-row>
              </div>
              <div v-show={this.selectedTemplate}>
                <div style="margin: 16px 0 8px;">配置基础参数</div>
                <el-form label-width="100px">
                  {this.getCurrentTemplate() &&
                    this.getCurrentTemplate().params.map(param => (
                      <el-form-item label={param.label} key={param.key}>
                        {param.type === "input" ? (
                          <el-input
                            vModel={this.paramValues[param.key]}
                            style="width:200px;"
                          />
                        ) : (
                          <el-select
                            vModel={this.paramValues[param.key]}
                            style="width:200px;"
                          >
                            {param.options.map(opt => (
                              <el-option label={opt} value={opt} key={opt} />
                            ))}
                          </el-select>
                        )}
                      </el-form-item>
                    ))}
                </el-form>
              </div>
              <div style="text-align:right;margin-top:16px;">
                <el-button type="primary" onClick={this.handleSave}>
                  保存
                </el-button>
              </div>
            </el-card>
          </div>
        );
      }
    },
    // 数据关联
    dataBinding: {
      props: ["sensors", "modelParams", "binding", "updateFrequency"],
      data() {
        return {
          localBinding: { ...this.binding },
          localFreq: this.updateFrequency || 1000
        };
      },
      methods: {
        handleSave() {
          this.$emit("save", {
            binding: { ...this.localBinding },
            updateFrequency: this.localFreq
          });
        }
      },
      render(h) {
        return (
          <el-card>
            <div slot="header">
              <span>数据关联设置</span>
            </div>
            <el-form label-width="120px">
              {Object.keys(this.modelParams || {}).map(param => (
                <el-form-item label={param} key={param}>
                  <el-select
                    vModel={this.localBinding[param]}
                    placeholder="选择传感器"
                    style="width:200px;"
                  >
                    {this.sensors.map(sensor => (
                      <el-option
                        label={sensor.name}
                        value={sensor.id}
                        key={sensor.id}
                      />
                    ))}
                  </el-select>
                </el-form-item>
              ))}
              <el-form-item label="数据更新频率">
                <el-select
                  vModel={this.localFreq}
                  style="width:200px;"
                  placeholder="选择频率"
                >
                  <el-option label="1秒" value={1000} />
                  <el-option label="5秒" value={5000} />
                  <el-option label="10秒" value={10000} />
                </el-select>
              </el-form-item>
            </el-form>
            <div style="text-align:right;">
              <el-button type="primary" onClick={this.handleSave}>
                保存
              </el-button>
            </div>
          </el-card>
        );
      }
    },
    // 可视化设置
    visualizationSetting: {
      props: ["structure", "visualConfig"],
      data() {
        return {
          localConfig: JSON.parse(JSON.stringify(this.visualConfig || {}))
        };
      },
      methods: {
        handleSave() {
          this.$emit("save", { ...this.localConfig });
        }
      },
      render(h) {
        return (
          <el-card>
            <div slot="header">
              <span>模型可视化设置</span>
            </div>
            <div>
              <div style="margin-bottom:8px;">设备结构层级</div>
              <el-tree
                data={this.structure}
                props={{ label: "name", children: "children" }}
                node-key="id"
                default-expand-all
                show-checkbox
                highlight-current
                vModel={this.localConfig.visibleParts}
                check-strictly
                onCheck={checked => (this.localConfig.visibleParts = checked)}
              />
            </div>
            <div style="margin:16px 0 8px;">关键部件状态展示方式</div>
            <el-form label-width="120px">
              {(this.structure || []).flatMap(part =>
                (part.children || []).map(child => (
                  <el-form-item label={child.name} key={child.id}>
                    <el-select
                      vModel={this.localConfig.displayMode?.[child.id]}
                      style="width:200px;"
                      placeholder="选择展示方式"
                    >
                      <el-option label="数值" value="value" />
                      <el-option label="进度条" value="progress" />
                      <el-option label="图标" value="icon" />
                    </el-select>
                  </el-form-item>
                ))
              )}
            </el-form>
            <div style="text-align:right;">
              <el-button type="primary" onClick={this.handleSave}>
                保存
              </el-button>
            </div>
          </el-card>
        );
      }
    },
    // 异常定位
    faultLocation: {
      props: ["structure", "sensorData", "faults", "binding"],
      data() {
        return {
          selectedFault: null
        };
      },
      computed: {
        faultList() {
          return this.faults || [];
        },
        partMap() {
          const map = {};
          (this.structure || []).forEach(part => {
            map[part.id] = part.name;
            (part.children || []).forEach(child => {
              map[child.id] = child.name;
            });
          });
          return map;
        }
      },
      render(h) {
        return (
          <el-card>
            <div slot="header">
              <span>异常检测与定位</span>
            </div>
            <el-row gutter={16}>
              <el-col span={8}>
                <el-table
                  data={this.faultList}
                  style="width:100%;"
                  highlight-current-row
                  onRow-click={row => (this.selectedFault = row)}
                  row-class-name={row =>
                    this.selectedFault && this.selectedFault.id === row.id
                      ? "selected-row"
                      : ""
                  }
                >
                  <el-table-column prop="name" label="异常名称" />
                  <el-table-column
                    prop="partId"
                    label="部件"
                    scopedSlots={{
                      default: scope =>
                        this.partMap[scope.row.partId] || scope.row.partId
                    }}
                  />
                </el-table>
              </el-col>
              <el-col span={16}>
                {this.selectedFault ? (
                  <div>
                    <h4>
                      {this.selectedFault.name}（
                      {this.partMap[this.selectedFault.partId]}）
                    </h4>
                    <el-table
                      data={this.selectedFault.relatedParams.map(paramId => ({
                        param: paramId,
                        value: this.sensorData[paramId],
                        sensor:
                          (this.binding &&
                            Object.keys(this.binding).find(
                              k => this.binding[k] === paramId
                            )) ||
                          paramId
                      }))}
                      style="width:100%;margin-top:8px;"
                    >
                      <el-table-column prop="param" label="参数" />
                      <el-table-column prop="value" label="当前值" />
                    </el-table>
                  </div>
                ) : (
                  <div style="color:#888;">请选择左侧异常进行定位</div>
                )}
              </el-col>
            </el-row>
          </el-card>
        );
      }
    }
  },
  data() {
    return {
      activeMenu: "modelConfig",
      deviceTypes,
      templates,
      sensors,
      deviceStructure,
      faults,
      // 状态数据
      modelConfig: this.loadLocal("modelConfig") || {
        deviceType: "",
        templateName: "",
        params: {}
      },
      dataBinding: this.loadLocal("dataBinding")?.binding || {},
      updateFrequency: this.loadLocal("dataBinding")?.updateFrequency || 1000,
      visualConfig: this.loadLocal("visualConfig") || {
        visibleParts: [],
        displayMode: {}
      },
      sensorRealtimeData: {},
      timer: null
    };
  },
  methods: {
    handleMenuSelect(key) {
      this.activeMenu = key;
    },
    saveModelConfig(config) {
      this.modelConfig = config;
      this.saveLocal("modelConfig", config);
      Message.success("模型配置已保存");
    },
    saveDataBinding({ binding, updateFrequency }) {
      this.dataBinding = binding;
      this.updateFrequency = updateFrequency;
      this.saveLocal("dataBinding", { binding, updateFrequency });
      Message.success("数据关联已保存");
      this.restartSensorTimer();
    },
    saveVisualConfig(config) {
      this.visualConfig = config;
      this.saveLocal("visualConfig", config);
      Message.success("可视化设置已保存");
    },
    saveLocal(key, value) {
      localStorage.setItem("dataModeling_" + key, JSON.stringify(value));
    },
    loadLocal(key) {
      try {
        return JSON.parse(localStorage.getItem("dataModeling_" + key));
      } catch {
        return null;
      }
    },
    updateSensorData() {
      this.sensorRealtimeData = genSensorRealtimeData(this.dataBinding);
    },
    restartSensorTimer() {
      if (this.timer) clearInterval(this.timer);
      this.updateSensorData();
      this.timer = setInterval(
        this.updateSensorData,
        this.updateFrequency || 1000
      );
    }
  },
  mounted() {
    this.restartSensorTimer();
  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer);
  }
};
</script>

<style scoped>
.data-modeling-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}
.side-menu {
  background: #fff;
  border-radius: 6px;
  min-height: 500px;
  margin-right: 8px;
}
.template-card.selected {
  border: 2px solid #409EFF;
}
.selected-row {
  background: #e6f7ff !important;
}
</style>
